package com.permission.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.permission.common.RequestHolder;
import com.permission.entity.SysUser;

import lombok.extern.slf4j.Slf4j;

/**
 * 拦截用户登录的请求
 * 每一个请求，在Filter里面判断，如果需要用到用户的数据的时候，我们就去取出来
 * 用户没有登录的时候跳转到用户登录页面
 * 用户已经登录的时候将信息通过RequestHolder.userHolder保存到 ThreadLocal
 * @author jing
 *
 */
@Slf4j
public class LoginFilter implements Filter{

	public void destroy() {
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request =  (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		
		SysUser user = (SysUser)request.getSession().getAttribute("user");
		if(user == null){
			//如果user是空的话，就跳转到登录页面
			String path = (request.getContextPath()+"/signin.jsp");
			response.sendRedirect(path);
			return;
		}	
		//如果user不为空，就说明登录成功，我们将信息保存，需要的时候可以通过RequestHolder获取
		RequestHolder.add(user);
		RequestHolder.add(request);
		//调用过滤链，让它继续 
		filterChain.doFilter(servletRequest, servletResponse);
		return;
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	/*
	 * LogiinFilter写完之后需要在web.xml配置
	 * 配置它拦截那些请求
	 */
}
